import {
  defineStore
} from 'pinia'
import {
  get,
  wxLogin,
  toast,
  getUrlParam,
  delUrlParam,
  randomStr
} from '../utils/helper.js'
import {
  isWx
} from '../utils/is.js'
const user = defineStore({
  id: 'user',
  state: () => ({
    isReady: null,
    onReady: null,
    isLogin: !!uni.getStorageSync('token'), // 登录状态
    info: {}, // 用户信息
    isWxLogin: !!uni.getStorageSync('wxId'),
    authType: 'smsLogin',
    agent: {}
  }),
	
  getters: {
    agentId: (state) => state.agent?.id ?? 0
  },

  actions: {
    /**
		 * pinia-user 初始化
		 */
    async init() {
      if (this.isLogin) {
        await this.getAgent()
      } else {
        if (!this.isWxLogin) {
          let client = 0
          let code = ''
          // #ifdef MP
          const miniRes = await wxLogin()
          client = 1
          code = miniRes.code
          // #endif
					
          // #ifdef H5
          if (getUrlParam('state', 'null') === uni.getStorageSync('wxRedirectState') && getUrlParam('code')) {
            uni.removeStorageSync('wxRedirectState')
            code = getUrlParam('code')
          } else if (isWx()) {
            // 第一次进入项目
            const wxRedirectState = randomStr(6)
            uni.setStorageSync('wxRedirectState', wxRedirectState)
            const scope = 'snsapi_base' // snsapi_userinfo=高级授权； snsapi_base=静默授权
            const redirectUri = delUrlParam(window.location.href, ['code', 'state', 'reduri'])
            const appid = 'wx0492d2cbed35043e'
            // 平台用的是公共域名，无需跳转APP_HOST下授权
            let authorUrl =
							`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${scope}&state=${wxRedirectState}#wechat_redirect`
            // 重定向到微信授权
            window.location.replace(authorUrl)
            return Promise.reject('未登录')
          }
          // #endif
          if (code) {
            const [authErr, authRes] = await get('/index/wxAuth', { code, client }, { isAsync: 1 })
            if (authErr) {
						  return toast(authErr.msg)
            }
            this.setWxLogin(authRes.data.wxId)
          }
        }
        uni.reLaunch({
          url: '/pages/index/login'
        })
        return Promise.reject('未登录')
      }
      typeof this.onReady === 'function' && this.onReady()
      return Promise.resolve({
        agent: this.agent
      })
    },
		
    setWxLogin(value = '') {
      uni.setStorageSync('wxId', value)
      this.isWxLogin = true
      return Promise.resolve({ value })
    },
		
    /**
		 * pinia-user 设置 token
		 */
    async setToken(value = '') {
      uni.setStorageSync('token', value)
      this.isLogin = true
      const agent = await this.getAgent()
      return Promise.resolve({
        token: value,
        agent
      })
    },
    /**
		 * pinia-user 清除 token
		 */
    clearToken() {
      uni.removeStorageSync('token')
      this.isLogin = false
      this.info = {}
    },
		
    // 获取设备信息
    async getAgent(id) {
      const res = await get('/user/agentInfo', { id })
      this.agent = res.success ? res.data : {}
      return Promise.resolve(this.agent)
    },
		
    /**
		 * pinia-user 获取个人信息
		 */
    async getInfo() {
      const [err, res] = await get('/User/index', {}, {
        isAsync: true
      })
      if (err) {
        return Promise.reject({
          msg: err.msg
        })
      }
      this.info = res.data

      return Promise.resolve(res.data)
    },
    /**
		 * pinia-user 登出
		 */
    async logout(force = false) {
      this.setToken()
    },

    setAuthType(value = '') {
      this.authType = value
    }
  }
})

export default user
